Class Inheritance

In javascript it is now possible to inherit all the methods of a class by another class.
We can inherit a class using extends keyword.

Example

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return 'I own a ' + this.carname;
  }
}

class Model extends Car {
  constructor(brand, model) {
    super(brand); // calls the construct of parent class.
    this.model = model;
  }
  show() {
    return this.present() + ', it is a ' + this.model;
  }
}

let myCar = new Model("Ford", "Mustang");
console.log(myCar.show()); // I own a Ford, it is a Mustang.

In the above example, the super() method is used to call the construct of the parent class.

Getters and Setters

In javascript, classes allows you to use getters and setters for your properties. This will be helpful when you want to perform any operation to the value before return the value.

Example

   class Company {
      constructor(brand) {
         this.companyName = brand;
      }
      get name() {
         return this.companyName;
      }
      set name(value) {
         this.companyName = value;
      }
   }
   let myCompany = new Company("ReadersBuddy");
   console.log(myCompany.name); // ReadersBuddy

In the above example, we created a class Company with property, companyName. To get and set the value of the property, we use get and set property.
Though the getter is a method, to get the value of the property we wont use the parentheses. Similary, though setter is a method, we wont use parentheses to set the value of the property.


Most Read